package com.jd.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jd.mapper.BookMapper;
import com.jd.mapper.EvaluationMapper;
import com.jd.mapper.MemberReadStateMapper;
import com.jd.pojo.Book;
import com.jd.pojo.Evaluation;
import com.jd.pojo.MemberReadState;
import com.jd.service.BookService;
import com.sun.tracing.dtrace.ArgsAttributes;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class BookServiceImpl implements BookService {
    @Autowired
    private BookMapper bookMapper;

    @Autowired
    private MemberReadStateMapper memberReadStateMapper;

    @Autowired
    private EvaluationMapper evaluationMapper;

    @Override
    public IPage<Book> Paging(Long categoryId,String order,Integer page, Integer rows) {
        //设置分页信息
        Page<Book> p=new Page<>(page,rows);
        //条件
        QueryWrapper queryWrapper=new QueryWrapper();

        if(categoryId!=null&&categoryId!=-1){
            queryWrapper.eq("category_id",categoryId);
        }

        if(order!=null){
            if(order.equals("quantity")){
                queryWrapper.orderByDesc("evaluation_quantity");
            }else if(order.equals("score")){
                queryWrapper.orderByDesc("evaluation_score");
            }
        }

        //执行查询
        IPage<Book> iPage= bookMapper.selectPage(p, queryWrapper);
        return iPage;
    }

    @Override
    public Book findBookById(Long bookId) {
        Book book = bookMapper.selectById(bookId);
        return book;
    }

    @Override
    public void updateEvaluation() {
        bookMapper.updateEvaluation();
    }

    @Override
    public void createBook(Book book) {
        bookMapper.insert(book);
    }

    @Transactional
    @Override
    public void deleteBook(Long bookId) {
        bookMapper.deleteById(bookId);

        QueryWrapper<MemberReadState> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("book_id",bookId);
        memberReadStateMapper.delete(queryWrapper);

        QueryWrapper<Evaluation> queryWrapper1=new QueryWrapper<>();
        queryWrapper.eq("book_id",bookId);
        evaluationMapper.delete(queryWrapper1);
    }

    //修改图书
    @Override
    public void updateBook(Book book) {
        bookMapper.updateById(book);
    }
}
